package com.smzd.utils.httpclient;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class Client {
    private static Client defaultClient = null;

    public static Client getDefaultClient() {
        if (defaultClient == null) {
            synchronized (Client.class) {
                if (defaultClient == null) {
                    defaultClient = new Client();
                }
            }
        }
        return defaultClient;
    }
    
    private HttpClient client;

    private Response lastResponse;
    
    public Request POST(String url){
        Request request = new Request(url, Request.METHOD_POST);
        request.setClient(this);
        return request;
    }
    public Request GET(String url){
        Request request = new Request(url, Request.METHOD_GET);
        request.setClient(this);
        return request;
    }

    public Response operate(Request request) throws Exception {
        consumeLastResponse();
        HttpUriRequest httpRequest = request.getHttpRequest();
        HttpResponse httpResponse = client.execute(httpRequest, localContext);
        Response response = new Response(httpResponse);
        printCookies();  
        response.setRequest(request);
        lastResponse = response;
        return response;
    }
    private void printCookies() {
        List<Cookie> cookies = cookieStore.getCookies();  
        for (int i = 0; i < cookies.size(); i++) {  
            System.out.println("Local cookie: " + cookies.get(i));  
        }
    }

    public Response operateWithRedirect(Request request) throws Exception {
        Response response = operate(request);
        if(response.isRedirectResponse()){
            String redirect = response.getRedirectPath();
            System.out.println("---is redirect response! redirect to: "+redirect);
            Request beforeRedirectRequest = response.getRequest();
            request = new Request(redirect);
            response = operateWithRedirect(request);
            response.setBeforeRedirectRequest(beforeRedirectRequest);
        }else{
            System.out.println("---is NOT redirect response!");
        }
        return response;
    }

    private void consumeLastResponse() {
        if (lastResponse != null) {
            lastResponse.consume();
            lastResponse = null;
        }
    }

    public Client() {
        initClient();
    }
    CookieStore cookieStore;
    HttpContext localContext;
    private void initClient() {
        //创建一个本地上下文信息  
        cookieStore = new BasicCookieStore();  
        localContext = new BasicHttpContext();  
        //在本地上下问中绑定一个本地存储  
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);  
        //创建HttpClient
        this.client = new DefaultHttpClient();
//       HttpHost proxy = new HttpHost("202.106.121.134", 80);
//       client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,proxy);
        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
        HttpConnectionParams
                .setConnectionTimeout(client.getParams(), 20 * 1000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 20 * 1000);
    }

    public void shutDown() {
        if (lastResponse != null) {
            lastResponse.consume();
        }
        this.client.getConnectionManager().shutdown();
    }

    public Client(HttpClient client) {
        this.client = client;
    }
    

    public static void main(String[] args) throws Exception {
        testLocalLogin();
//      Response response = test1(client);
//      Client client = new Client();
//      Request request = client.POST("http://localhost:8080/twx/test/upload");
//      request.addParameter("mediatype", "image").addFile("file", new File("e:/1.jpg"));
//      Response response = request.execute();
//      StringBuffer sb = response.getResponseContent();
//      System.out.println(sb);
    }
    private static void testLocalLogin() throws Exception {
//      String client_id="bc00e07e-c1a8-419f-bb1b-a1d98b4af2ff";
        Client client = new Client();
        Request req = client.GET("http://localhost:8080/xin2core/local/login?username=super&password=super");
        Response resp = req.execute();
        if(resp.isRedirectResponse()){
            System.out.println("Expected!!!");
            System.out.println("redirect to : "+resp.getRedirectPath());
        }
        
    }
    static Response test1(Client client) throws Exception {
        Request request = new Request("http://localhost:8080/sparklr2",
                Request.METHOD_GET);
        client.operate(request);
        request = new Request("http://localhost:8080/sparklr2/login.do",
                Request.METHOD_POST);
        request.addParameter("j_username", "marissa");
        request.addParameter("j_password", "koala");
        Response response = client.operate(request);
        if (response.isRedirectResponse()) {
            String redirectPath = response.getRedirectPath();
            request = new Request(redirectPath, Request.METHOD_GET);
            response = client.operate(request);
        }else{
            System.out.println("------is not redirect response!");
        }
        return response;
    }
}
